import os
import dify_helper
import pandas as pd
import argparse
import json

def load_jsonl(file_path):
    data = []
    with open(file_path, 'r') as file:
        for line in file:
            json_obj = json.loads(line)
            data.append(json_obj)
    return data

def save_jsonl(data, file_path):
    with open(file_path, 'a') as file:
        for json_obj in data:
            file.write(json.dumps(json_obj) + '\n')
    return file_path
def run_dify(question_data:dict,dh:dify_helper.DifyHelper):
    options_str = ""
    for ov in question_data["options"]:
        options_str += "{}\n".format(ov)
    question_str = "{}\n{}".format(question_data["question"],options_str)
    paramters = {
        "question":question_str
    }
    print(paramters)
    try:
        res_body = dh.send_workflow(paramters)
        print(res_body)
        answer = res_body["is_film_question"]
    except Exception as ex:
        print(ex)
        answer = "False"
    # print(answer)
    return answer

def run_dify_batch(raw_jsonl_path:str,filted_jsonl_path:str,dh:dify_helper.DifyHelper):
    data_arr = load_jsonl(raw_jsonl_path)
    f_question_arr = []
    for question_data in data_arr:
        answer = run_dify(question_data,dh)
        if answer.lower() == "false":
            continue
        n_opttions = {}
        for opt_idx,opt in enumerate(question_data["options"]):
            n_opttions[chr(65+opt_idx)] = opt
        question_data["options"] = n_opttions
        answer_idx = question_data["answer"]
        answer_str = n_opttions[question_data["answer"]]
        question_data["answer"] = answer_str
        question_data["answer_idx"] = answer_idx
        f_question_arr.append(question_data)
    save_jsonl(f_question_arr,filted_jsonl_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="dify批量运行器")
    parser.add_argument('-rjp',"--raw_jsonl_path", type = str, help = "原始jsonl文件地址")
    parser.add_argument('-fjp',"--filted_jsonl_path", type = str, help = "过滤后jsonl文件地址")
    args = parser.parse_args()
    raw_jsonl_path = args.raw_jsonl_path
    filted_jsonl_path = args.filted_jsonl_path
    dh = dify_helper.DifyHelper("http://39.96.64.172:18863/v1","app-EWsZgYdnL5MDMQZKtFKCPMa7")
    run_dify_batch(raw_jsonl_path,filted_jsonl_path,dh)